<template>
  <div class="nav-tab">
    <el-row class="nav-content">
      <el-col :span="3">
        <router-link to="/index" class="logo">
          <img :src="logoUrl" alt="Logo"/>
        </router-link>
      </el-col>
      <el-col :span="21" class="nav-item-box">
        <div class="menu-toggle" @click="toggleMenu" v-if="isMobile">
          <i class="el-icon-menu"></i>
        </div>
        <ul class="nav-box" :class="{ 'mobile-nav': isMobile, 'active': isMenuOpen }" v-if="!isMobile">
          <li v-for="(item, index) in navItems" :key="index"
              :class="{active: isTransportActive(index)}">
            <el-dropdown v-if="item.children"
                         trigger="hover"
                         :hide-on-click="false"
                         @command="handleCommand">
              <span
                class="el-dropdown-link nav-item"
                @click="handleTitleClick(item, index)"
                style="user-select: none;"
              >
                {{ getLocalizedTitle(item) }}
                <i class="el-icon-arrow-down el-icon-caret-bottom"></i>
              </span>
              <el-dropdown-menu slot="dropdown" class="custom-dropdown">
                <el-dropdown-item
                  v-for="(child, childIndex) in item.children"
                  :key="childIndex"
                  :command="{parentIndex: index, childIndex: childIndex}"
                  :class="{selected: isTransportChildActive(index, childIndex)}"
                >
                  {{ getLocalizedChildTitle(child) }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <router-link v-else :to="item.path" class="nav-item" @click.native="closeMenuIfMobile">
              {{ getLocalizedTitle(item) }}
            </router-link>
          </li>
        </ul>
        <!-- 移动端菜单 -->
        <div class="mobile-menu" v-if="isMobile">
          <el-drawer
            :visible.sync="isMenuOpen"
            direction="ltr"
            size="80%"
            :with-header="false"
            custom-class="mobile-drawer"
            :modal="false"
          >
            <el-menu
              :default-active="activeMobileMenu"
              class="el-menu-vertical-demo"
              @select="handleMobileMenuSelect"
              background-color="#fff"
              text-color="#333"
              active-text-color="#fe3231"
            >
              <template v-for="(item, index) in navItems">
                <el-submenu v-if="item.children" :index="String(index)" :key="index">
                  <template slot="title">
                    <span @click.stop="handleTitleClick(item, index)">
                      {{ getLocalizedTitle(item) }}
                    </span>
                  </template>
                  <el-menu-item
                    v-for="(child, childIndex) in item.children"
                    :key="childIndex"
                    :index="item.children[childIndex].path"
                  >
                    {{ getLocalizedChildTitle(child) }}
                  </el-menu-item>
                </el-submenu>
                <el-menu-item
                  v-else
                  :index="item.path"
                  :key="index"
                >
                  {{ getLocalizedTitle(item) }}
                </el-menu-item>
              </template>
            </el-menu>
          </el-drawer>
          <div class="menu-toggle" @click="toggleMenu">
            <i class="el-icon-menu"></i>
          </div>
        </div>
        <div class="right-area">
          <div class="message-icon">
            <img :src="mesUrl" alt="Messages"/>
          </div>
          <el-dropdown trigger="click" @command="handleSetLanguage" ref="langDropdown">
            <span class="el-dropdown-link lang-selector">
              {{ currentLang }}
            </span>
            <el-dropdown-menu slot="dropdown" class="custom-dropdown">
              <el-dropdown-item
                v-for="lang in languages"
                :key="lang.value"
                :command="lang.value"
                :class="{selected: currentLang === lang.label}"
              >
                {{ lang.label }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import Cookies from "js-cookie";

export default {
  name: 'NavBar',
  data() {
    return {
      logoUrl: require('@/assets/asl_images/logo.png'),
      mesUrl: require('@/assets/asl_images/language.svg'),
      languages: [
        {label: 'Deutsch', value: 'de'},
        {label: 'English', value: 'en'},
        {label: '中文', value: 'zh'}
      ],
      currentTransportIndex: 0,
      isMenuOpen: false,
      isMobile: false
    }
  },
  computed: {
    ...mapGetters(['language']),
    currentLang() {
      const lang = this.languages.find(item => item.value === (this.language || 'de'))
      return lang ? lang.label : 'English'
    },
    navItems() {
      return [
        {
          title: "navDetails.InternationalTransport",
          path: '/index',
          children: [
            {title: 'navDetails.RailTransport', path: '/transport/rail'},
            {title: 'navDetails.SeaFreight', path: '/transport/sea'},
            {title: 'navDetails.AirCargo', path: '/transport/air'},
            {title: 'navDetails.RoadTransport', path: '/transport/road'}
          ]
        },
        {
          title: 'navDetails.Services',
          path: '/services',
          children: [
            {title: 'navDetails.Warehousing', path: '/services/warehousing'},
            {title: 'navDetails.Customs', path: '/services/customs'},
            {title: 'navDetails.Ecommerce', path: '/services/ecommerce'},
            {title: 'navDetails.Oversize', path: '/services/oversize'},
            {title: 'navDetails.ProjectCargo', path: '/services/project-cargo'}
          ]
        },
        {
          title: 'navDetails.Quotes',
          children: [
            {title: 'navDetails.myASLAccount', path: '/quote'},
            {title: 'navDetails.Quotation', path: '/quote'},
            {title: 'navDetails.Order', path: '/quote'},
          ]
        },
        {title: 'navDetails.Tracking', path: '/tracking'},
        {
          title: 'navDetails.AboutUs',
          path: '/about/company',
          children: [
            {title: 'navDetails.CompanyProfile', path: '/about/company'},
            {title: 'navDetails.CooperationNetwork', path: '/about/partners'},
            {title: 'navDetails.Joinus', path: '/about/join'},
            {title: 'navDetails.Contactus', path: '/about/contact'},
          ]
        }
      ]
    }
  },
  created() {
    if (!Cookies.get('language')) {
      this.$i18n.locale = 'de'
      this.$store.dispatch('app/setLanguage', 'de')
      Cookies.set('language', 'de')
    }
    this.updateActiveState()
    this.checkScreenSize()
    window.addEventListener('resize', this.checkScreenSize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.checkScreenSize)
  },
  watch: {
    '$route'(to) {
      this.updateActiveState()
    },
    language(newVal) {
      this.$i18n.locale = newVal
    }
  },
  methods: {
    getLocalizedTitle(item) {
      return this.$t(item.title)
    },
    getLocalizedChildTitle(child) {
      return this.$t(child.title)
    },
    closeMenuIfMobile() {
      if (this.isMobile) {
        this.isMenuOpen = false;
      }
    },
    handleSetLanguage(lang) {
      this.$i18n.locale = lang
      this.$store.dispatch('app/setLanguage', lang)
      Cookies.set('language', lang)
      this.$message({
        message: this.$t('language.changeSuccess'),
        type: 'success'
      })
      this.$router.go(0)
    },
    handleMobileMenuSelect(index) {
      this.isMenuOpen = false;
      this.activeMobileMenu = index;
      this.$router.push(index);
    },
    handleCommand(command) {
      const selectedItem = this.navItems[command.parentIndex].children[command.childIndex]
      if (command.parentIndex === 0) {
        this.currentTransportIndex = command.childIndex
      }
      this.$router.push(selectedItem.path);
    },
    handleTitleClick(item, index) {
      // 点击“国际运输”主菜单，跳转首页
      if (item.title === "navDetails.InternationalTransport") {
        this.$router.push('/index');
        if (this.isMobile) {
          this.isMenuOpen = false;
        }
      }
    },
    updateActiveState() {
      if (this.$route.path.startsWith('/transport')) {
        const path = this.$route.path.split('/')[2]
        const index = this.navItems[0].children.findIndex(
          child => child.path.includes(path)
        )
        this.currentTransportIndex = index > -1 ? index : 0
      }
      this.activeMobileMenu = this.$route.path;
    },
    isTransportActive(index) {
      if (index === 0) {
        return this.$route.path.startsWith('/transport')
      }
      return this.navItems[index].path === this.$route.path
    },
    isTransportChildActive(parentIndex, childIndex) {
      if (parentIndex === 0) {
        const transportPath = this.navItems[0].children[childIndex].path
        return this.$route.path === transportPath
      }
      return false
    },
    toggleMenu() {
      this.isMenuOpen = !this.isMenuOpen
    },
    checkScreenSize() {
      this.isMobile = window.innerWidth < 768
      if (this.isMobile) {
        this.isMenuOpen = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.nav-tab {
  width: 100%;
  height: 90px;
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  user-select: none;
  cursor: pointer;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
}

.nav-content {
  width: 1200px;
  height: 100%;
  margin: 0 auto;
  display: flex;
  align-items: center;
}

.logo {
  height: 100%;
  display: flex;
  align-items: center;

}

.nav-box {
  display: flex;
  justify-content: center;
  height: 100%;

  li {
    height: 100%;
    display: flex;
    align-items: center;
    padding: 0 15px;
    position: static;

    .el-dropdown-link {
      cursor: pointer;
    }

    &.active {
      .nav-item, .el-dropdown-link {
        color: #fe3231;
      }
    }

    &:hover {
      .nav-item, .el-dropdown-link {
        color: #fe3231;
      }
    }

    .nav-item, .el-dropdown-link {
      color: #333;
      font-size: 18px;
      font-weight: 500;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #fe3231;
      }
    }
  }
}

.el-icon-caret-bottom {
  font-size: 20px;
}

.right-area {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 100%;

  .message-icon {
    margin-right: 10px;
    cursor: pointer;

    img {
      height: 24px;
      width: auto;
      vertical-align: bottom;
      max-width: none;
      max-height: none;
    }
  }

  .lang-selector {
    color: #333;
    font-size: 18px;

    &:hover {
      color: #fe3231;
    }
  }
}

.custom-dropdown {
  .el-dropdown-menu__item {
    font-size: 16px;
    color: #333;
    width: 200px;
    padding: 10px 20px;
    line-height: 36px;
    text-align: center;

    &:hover {
      color: #fe3231;
      background: none;
    }

    &.selected {
      color: #fe3231;
      background: none;
      font-weight: 500;
    }
  }
}

.nav-item-box {
  display: flex;
  align-items: center;
}

.menu-toggle {
  display: none;
  font-size: 24px;
  cursor: pointer;
  color: #333;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .nav-content {
    width: 100%;
    padding: 0 15px;
  }

  .menu-toggle {
    display: block;
    position: absolute;
    right: 50%;
    top: 30px;
    z-index: 1001;
  }

  .nav-box {
    position: fixed;
    top: 70px;
    left: 0;
    width: 100%;
    background: #fff;
    flex-direction: column;
    padding: 0;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.3s ease;
    z-index: 1000;

    &.mobile-nav.active {
      max-height: 50vh; /* 半屏高度 */
    }

    li {
      width: 100%;
      padding: 15px;
      border-bottom: 1px solid #f0f0f0;
      display: flex;
      justify-content: flex-start;

      .el-dropdown-link {
        display: flex;
        justify-content: space-between;
        width: 100%;
      }

      .nav-item {
        width: 100%;
      }
    }
  }

  .right-area {
    margin-left: 70%; /* 增加右侧间距 */
  }

  .logo {
    margin-left: 15px;
  }
}

body {
  padding-top: 90px;
}
</style>
